package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")//这个注解代表是一个拦截器,先对所有路径进行拦截
public class LoginCheckFilter implements Filter {
    //定义一个公共常量用来匹配路径,这个类中的方法可以匹配通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取当前访问路径
        String uri = request.getRequestURI();
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
        //2.判断当前访问路径是否直接放行
        if (check(uri,uris)){
            //是我们之前定义的路径,直接放行
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("user")!=null){
            User user = (User) request.getSession().getAttribute("user");
            Long id = user.getId();
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);
            BaseContext.remove();
            return;
        }
        //如果不是就需要判断是否登录
        if (request.getSession().getAttribute("employee")!=null){
           // long threadId = Thread.currentThread().getId();

            Employee emp = (Employee) request.getSession().getAttribute("employee");
            Long id = emp.getId();
            BaseContext.setCurrentId(id);
            //这里代表不为空,已经登录过了,放行
            filterChain.doFilter(request,response);
            BaseContext.remove();
            return;
        }
        //其他情况都是需要跳转到登录页面的情况
        R<Object> r = R.error("NOTLOGIN");
        //将对象转换为json对象,传给前端
        ObjectMapper mapper = new ObjectMapper();
        String jsonr = mapper.writeValueAsString(r);
        //再用输出流传给前端
        response.getWriter().write(jsonr);
        return;//return  结束方法
    }

    public boolean check(String uri, String[] uris) {
        for (String s : uris) {
            if (PATH_MATCHER.match(s, uri)) {
                return true;
            }
        }
        return false;
    }
}
